<?php defined('SYSPATH') or die('No direct access allowed.');

class OpenLogin_QQ extends OpenLogin
{
    public function get_login_url($type="TOURIST")
    {
        $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
        .$this->_app_key . "&redirect_uri=" . urlencode($this->_callback_url.'?type='.$type) . "&state=" . $this->state();
        return $url;
    }

    public function get_access_token()
    {
        $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&" .
        "client_id=" . $this->_app_key . "&redirect_uri=" . urlencode($this->_callback_url) .
        "&client_secret=" . $this->_app_secret . "&code=" . (empty($_REQUEST['code']) ? '' : $_REQUEST['code']);
        $res = array();
        parse_str(file_get_contents($token_url), $res);
        return Arr::get($res, 'access_token');
    }
    
    public function get_openid($access_token)
    {
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $access_token;
        $str = file_get_contents($graph_url);
        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str = substr($str, $lpos + 1, $rpos - $lpos - 1);
        }
        $info = json_decode($str, true);
        return Arr::get($info, 'openid');
    }

    public function get_user_info($openid, $access_token)
    {
        $get_user_info = "https://graph.qq.com/user/get_user_info?" . "access_token=" .
            $access_token . "&oauth_consumer_key=" . $this->_app_key . "&openid=" . $openid .
            "&format=json";
        $str = file_get_contents($get_user_info);
        $arr = json_decode($str, true);
        if (empty($arr)) return $arr;
        if (!empty($user['error'])) return false;
        
        $info['uid']     = $openid;
        $info['userToken']  = $access_token;
        $info['gender']     = $arr['gender'];
        $info['nickname']   = $arr['nickname'];
        $info['header_url'] = $arr['figureurl_qq_2'];
        return $info;
    }
}